package  com.sat.common.utils

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import  com.sat.common.base.BaseAPP
import java.io.File
import java.io.IOException

object CameraUtil {
    fun openCamera(
        activity: Activity,
        requestCode: Int,
        path: String?
    ) {
        val mIntent =
            Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        val authority = activity.packageName + ".fileProvider"
        val file = File(path)
        if (!file.exists()) {
            file.parentFile.mkdirs()
            try {
                file.createNewFile()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        val uri: Uri = getUriWithFile(BaseAPP.getContext(), file, authority)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //第二个参数为 包名.fileprovider
            mIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }
        mIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
        activity.startActivityForResult(mIntent, requestCode)
    }

    fun openCamera(
        activity: Fragment,
        requestCode: Int,
        path: String?
    ) {
        val mIntent =
            Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        val authority = activity.context!!.packageName + ".fileProvider"
        val file = File(path)
        if (!file.exists()) {
            file.parentFile.mkdirs()
            try {
                file.createNewFile()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        val uri: Uri = getUriWithFile(BaseAPP.getContext(), file, authority)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //第二个参数为 包名.fileprovider
            mIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }
        mIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
        activity.startActivityForResult(mIntent, requestCode)
    }

    fun getUriWithFile(
        context: Context?,
        file: File?,
        authority: String?
    ): Uri {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //第二个参数为 包名.fileprovider
            FileProvider.getUriForFile(context!!, authority!!, file!!)
        } else {
            Uri.fromFile(file)
        }
    }
}
